import { Navigate, useNavigate, useLocation, Outlet } from "react-router-dom";
import { useEffect } from "react";
import globalStore from "../store/globalStore";
import request from "../api";
import globalBus from "../store/globalBus";
const { reqSomeRoult } = request;
export default function IsLogin() {
  const navigate = useNavigate();
  const loacation = useLocation();
  const token = localStorage.getItem("token");
  const getRoules = async () => {
    const result = (await reqSomeRoult(Number(token) || 0)) as unknown as any;
    if (
      result[0] &&
      result[0].rights instanceof Array &&
      result[0].rights.length > 0
    ) {
      globalBus.asyncChangeState("changeRouter", [result[0].rights]);
      globalStore.data.roules = result[0].rights;
    }
  };

  if (token) {
    useEffect(() => {
      if (loacation.pathname === "/main") {
        navigate("home");
      }
      getRoules();
    }, []);
    return (
      <div style={{ padding: "20px", height: "92%" }}>
        <Outlet />
      </div>
    );
  }
  return <Navigate to="/login"></Navigate>;
}
